<template>
    <div class="warp" style="height:100%;">
        <div>
            <navbar :title="$t('mod_exit_save')" v-show="!isHorizontalScreen" :backCallback="leave">
                <template #right>
                    <a class="add-btn" style="color: #000" v-if="isDown && isIos" @click="downloadFileIos(src)" >
                    {{ $t('lab_download') }}
                    </a>
                    <a class="add-btn" style="color: #000" v-if="isDown && !isIos" :href="src" download >
                        {{ $t('lab_download') }}
                    </a>
                    <div class="header-icon" v-if="!isDown && isShowRotateIcon">
                        <i class="rotate-icon" @click="rotate"></i>
                    </div>
                </template>
            </navbar>
        </div>
        <div class="header-title-01 header-title-05 horizontal-screen" @click.once="leave()" v-show="isHorizontalScreen">
            <span class="icon-back"></span>
            <h1 class="title" :style="{'width': curLan === 'en' ? '48px' : '20px'}">
                <span v-html="$t('mod_exit_save_2')"></span>
            </h1>
        </div>
        <div class="content-noBottom">
            <div style="height: 100%;" :style="{'width': isHorizontalScreen ? 'calc(100% - 48px)' : '100%'}">
                <iframe v-if="file" :src="idvUrl" style="height: 100%;" width="100%" scrolling="yes" frameborder="0"/>
<!--                <img :src="previewUrl" v-if="img" alt="" width="100%"/>-->
<!--                <div class="detail-video" v-if="video">-->
<!--                    <div class="video-icon-box" @click="playVideo()" :style="{'display': isPlayVideo ? 'none' : 'inline-block'}">-->
<!--                        <span class="video-icon"></span>-->
<!--                    </div>-->
<!--                    <video :data-idkey="modId" ref="video" :src="previewUrl" controls controlslist="nodownload"></video>-->
<!--                </div>-->
                <!--<video v-if="video" :src="previewUrl" controls></video>-->
            </div>
        </div>
        <verification-code v-if="isHandUp" @overtime-code="handleOverTime" @pass-code="passCode"></verification-code>
    </div>
</template>

<script>
import verificationCode from '@/repeatComponents/verification-code/verification-code';
import { getDate } from '@/utils/tools';
export default {
    name: 'TeachingMaterial',
    components: {
        verificationCode
    },
    data() {
        return {
            overTime: false, // 是否超时
            isHandUp: false,
            modHangUpTime: 0, // 防挂机间隔时间
            handTimer: {}, // 定时器
            handTimes: 0, // 定时器初始时间（s）
            handCurTime: 0, // 视频断点上一次续播时间（用于防挂机）
            src: '',
            isDown: false,
            video: false,
            previewUrl: '',
            file: false,
            img: false,
            startTime: new Date().getTime(),
            data: {},
            isPlayVideo: false,
            cov_status: '',
            modId: this.$route.params.modId,
            isHorizontalScreen: true,
            screenWidth: document.body.clientWidth,
            screenHeight: document.body.clientHeight,
            curLan: window.localStorage.getItem('globalLang'),
            /*新的参数*/
            resource: '', //资源地址
            idvUrl: '',
            palpitate: {
                isPause: false, // 是否暂停
                itmId: '', // 课程itmId
                modId: '', // 模块resId
                tkhId: '' // 学习跟踪id
            },
            times: null,
            isShowRotateIcon: false, // 是否显示旋转图标
            isRotate: false // 是否旋转，默认为竖屏
        };
    },
    methods: {
        isDoc(fileExt) {
            if (!fileExt) {
                return false;
            }
            fileExt = fileExt.substring(0, 3).toLowerCase();
            if (fileExt === 'doc' || fileExt === 'xls' || fileExt === 'ppt' || fileExt === 'pdf' || fileExt === 'txt') {
                return true;
            }
            return false;
        },
        // 保存学习记录
        saveRecord(leave = false) {
            this.$toast(this.$t('mod_save_record'));
            const req = {
                entId: this.$route.params.userEntId,
                itmId: this.$route.params.itmId,
                modId: this.$route.params.modId,
                startTime: this.startTime,
                tkhId: this.$route.params.tkhId
            };
            this.$axios({
                method: 'POST',
                url: `/app/api/trainee/course/module/evaluation`,
                data: req
            }).then(res => {
                if (leave) {
                    return true;
                }
            });
        },
        leave(times) {
            // console.log(this.cur_time);
            if (!this.overTime) {
                this.$toast(this.$t('mod_save_record'));
                const req = {
                    entId: this.$route.params.userEntId,
                    itmId: this.$route.params.itmId,
                    modId: this.$route.params.modId,
                    startTime: this.startTime,
                    tkhId: this.$route.params.tkhId
                };
                if (times) {
                    req.codeInputTime = times;
                }
                this.$axios({
                    method: 'POST',
                    url: `/app/api/trainee/course/module/evaluation`,
                    data: req
                }).then(res => {
                    if (times) {
                        // this.startTime = res.data;
                        this.overTime = false;
                    } else {
                        this.$router.go(-1);
                    }
                });
            } else {
                this.$router.go(-1);
            }
        },
        /*视频播放*/
        playVideo() {
            this.isPlayVideo = true;
            this.$refs.video.play();
        },
        changeHorizontalScreen() {
            if (this.screenWidth > this.screenHeight) {
                this.isHorizontalScreen = true;
            } else {
                this.isHorizontalScreen = false;
            }
        },
        getModuleDetail() {
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/course/module/detail`,
                params: {
                    itmId: this.$route.params.itmId,
                    modId: this.$route.params.modId
                }
            }).then(res => {
                if (res && res.status === 200) {
                    this.resource = res.data.sourceUrl;
                    this.startTime = res.data.startTime;
                    this.isDown = res.data.relationVO.modDownloadInd;
                    this.modHangUpTime = res.data.modHangUpTime;
                    this.src = this.appUrl + res.data.sourceUrl;
                    this.getIdvUrl(this.resource);
                    // 若设置了防挂机间隔时间，则初始化定时器。倒计时结束打开弹窗
                    if (this.modHangUpTime && this.modHangUpTime !== 0) {
                        this.handTime();
                    } else {
                        this.palpitateTime();
                        this.times = setInterval(() => {
                            this.palpitateTime();
                        }, 5000);
                    }
                }
            });
        },
        //idv
        getIdvUrl(data) {
            this.$axios({
                method: 'GET',
                url: `/app/idv/previewUrl`,
                params: {
                    filePath: data
                }
            }).then(res => {
                this.file = true;
                this.idvUrl = res.data;
                console.log(this.idvUrl);
            });
        },
        //  学习心跳
        palpitateTime() {
            this.$axios({
                method: 'POST',
                url: '/app/api/trainee/course/learn/heartbeat',
                data: this.palpitate
            });
        },
        /**
     * @description: 防挂机间隔定时器
     * @param {*}
     * @return {*}
     */
        handTime() {
            this.handTimes = this.modHangUpTime * 10;
            this.handTimer = setInterval(() => {
                this.handTimes--;
                if (this.handTimes === 0) {
                    clearInterval(this.handTimer);
                    this.isHandUp = true;
                    this.overTime = true;
                }
            }, 1000);
            this.$once('hook:beforeDestroy', () => {
                clearInterval(this.handTimer);
            });
        },
        /**
         * @description: 防挂机超时处理
         * @param {*}
         * @return {*}
         */
        handleOverTime() {
            this.overTime = true;
            this.leave();
        },
        /**
         * @description: 通过防挂机验证，继续学习
         * @param {*}
         * @return {*}
         */
        passCode(times) {
            this.isHandUp = false;
            this.overTime = false;
            this.leave(times);
            this.handTime();
        },
        onlineCalculation(type) {
            this.$axios({
                method: 'GET',
                url: `/app/api/data/kanban/online/${type}/calculate`
            }).then(res => {
                console.log(res);
            });
        },
        // 横屏
        onLandscape() {
            if (window.plus) {
                window.plus.screen.lockOrientation('landscape-primary');
            }
        },
        // 竖屏
        onPortrait() {
            if (window.plus) {
                window.plus.screen.lockOrientation('portrait-primary');
            }
        },
        /**
         * 旋转 */
        rotate() {
            this.isRotate = !this.isRotate;
            if (this.isRotate) {
                this.onLandscape(); // 横屏
            } else {
                this.onPortrait(); // 竖屏
            }
        }
    },
    mounted() {
        if (window.plus) {
            this.isShowRotateIcon = true;
        }
        this.palpitate.itmId = this.$route.params.itmId;
        this.palpitate.modId = this.$route.params.modId;
        this.palpitate.tkhId = this.$route.params.tkhId;
        //防止页面刷新,cov_status值丢失
        if (this.$store.getters.getDetail) {
            if (this.$store.getters.getDetail.courseEvaluation) {
                window.localStorage.setItem('temp_cov_status', this.$store.getters.getDetail.courseEvaluation.cov_status);
            }
        }
        this.cov_status = window.localStorage.getItem('temp_cov_status');
        //断点播放视频
        this.breakpointplay(this);
        //监听屏幕宽高的变化
        window.onresize = () => {
            this.screenWidth = document.body.clientWidth;
            this.screenHeight = document.body.clientHeight;
        };
        this.changeHorizontalScreen();
        this.onlineCalculation('ONLINE_LEARN_INC');
    },
    destroyed() {
        this.onlineCalculation('ONLINE_LEARN_DEC');
        this.onPortrait();
    },
    created() {
        /**获取课程详情**/
        this.getModuleDetail();
    },
    beforeRouteLeave(to, from, next) {
        if (!this.overTime) {
            this.saveRecord();
        }
        next();
    },
    beforeDestroy() {
        clearInterval(this.times);
        this.times = null;
    },
    watch: {
        screenWidth(val) {
            this.changeHorizontalScreen();
        },
        screenHeight(val) {
            this.changeHorizontalScreen();
        }
    }
};
</script>

<style scoped lang="less">
    *{
        font-size: 14px;
    }
    .content-noBottom {
        padding: 0;
        padding-top: 56px;
        height: calc(100% - 56px);
    }
    .detail-video {
        position: relative;
        width: 100%;
        min-height: 200px;
        max-height: 250px;
    }
    .detail-video .video-icon-box {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 5;
    }
    .detail-video .video-icon{
        width: 56px;
        height: 56px;
        display: flex;
        border-radius: 100%;
        background: rgba(0,0,0,.5);
        position: absolute;
        justify-content: center;
        align-items: center;
        top: 50%;
        margin-top: calc(-56px / 2);
        left: 50%;
        margin-left: calc(-56px / 2);
        z-index: 6;
    }
    .detail-video .video-icon:after{
        content: '';
        display: block;
        width: 15px;
        height: 20px;
        background: url(../../../static/images/icon-05.png) no-repeat 1px -2px;
        background-size: 15px;
    }
    .detail-video video{
        width: 100%;
        /*height: 100%;*/
        max-height: 250px;
        position: relative;
        z-index: 2;
    }
    .horizontal-screen {
        width: 48px;
        height: 100%;
        position: absolute;
        top: 0;
        right: 0;
        background: #ffffff;
        padding: 0;
        .title {
            margin: 0 auto;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            font-size: 1.2em;
            color: #1a1a1a;
            font-weight: bold;
            text-align: center;
        }
        @media screen and (max-height: 30px) {
            .title {
                width: 28px;
                font-size: 0.8em;
            }
        }
    }
    .add-btn {
        height: 55px;
        line-height: 55px;
        padding: 0 15px;
        font-size: 16px;
        color: #000;
    }
    /deep/.code-popup{
      min-width: 80%;
    }
    .header-icon{
        width: 54px;
    }
    .rotate-icon{
        display: inline-block;
        width: 100%;
        height: 56px;
        background: url('../../../static/images/icon1.png') no-repeat;
        background-size: 35px;
        background-position: 5px;
    }
    /deep/.van-nav-bar__title {
        margin: 0 10px;
    }
</style>
